<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px" @close="close" :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="编码" prop="unitCode">
        <el-input v-model.trim="form.unitCode" autocomplete="off" maxlength="50" placeholder="请输入单位编码"></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="unitName">
        <el-input v-model.trim="form.unitName" autocomplete="off" maxlength="50" placeholder="请输入单位名称"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { doAdd, doEdit } from '@/api/basics/unit'

  export default {
    name: 'UnitEdit',
    data() {
      return {
        form: {
          unitCode: '',
          unitName: '',
        },
        rules: {
          unitCode: [{ required: true, trigger: ['blur', 'change'], message: '请输入编码' }],
          unitName: [{ required: true, trigger: ['blur', 'change'], message: '请输入名称' }],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    created() {},
    methods: {
      showEdit(row) {
        if (!row) {
          this.title = '新增'
        } else {
          this.title = '编辑'
          this.form = Object.assign({}, row)
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (this.form.unitId) {
              await doEdit(this.form).then((res) => this.callbackFun(res))
            } else {
              await doAdd(this.form).then((res) => this.callbackFun(res))
            }
          } else {
            return false
          }
        })
      },
      callbackFun(res) {
        if (res.success) {
          this.$baseMessage(res.msg, 'success')
          this.$emit('fetch-data')
          this.close()
        } else {
          this.$baseMessage(res.msg, 'error')
        }
      },
    },
  }
</script>
